package com.sincebest.fivestar.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSONObject;

/*
 * RestClient
 * 发http请求，返回JSON
 */
public class RestClient {

	private static String ENCODING = "UTF-8";

	public static JSONObject postJson(String url, Map<String, Object> paramsMap) {
		String resp = post(url, paramsMap);
		JSONObject obj = JSONObject.parseObject(resp);
		return obj;
	}
	
	public static JSONObject getJson(String url, Map<String, String> paramsMap) {
		String resp = get(url, paramsMap);
		JSONObject obj = JSONObject.parseObject(resp);
		return obj;
	}


	/**
	 * post请求, 返回响应的状态码
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	public static int fetchPostRespStatus(String url, Map<String, String> paramsMap) {
		int statusCode = -1;

		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			HttpPost method = new HttpPost(url);
			if (paramsMap != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
					paramList.add(pair);
				}
				method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
			}
			response = client.execute(method);
			statusCode = response.getStatusLine().getStatusCode();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusCode;
	}


	/**
	 * 基于HttpClient 4.3的POST方法
	 *
	 * @param url       提交的URL
	 * @param paramsMap 提交<参数，�?>Map
	 * @return 响应文本内容
	 */
	public static String post(String url, Map<String, Object> paramsMap) {
		CloseableHttpClient client = HttpClients.createDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost method = new HttpPost(url);
			StringEntity s = new StringEntity(JsonTools.jsonSer(paramsMap));  
			s.setContentEncoding("UTF-8");  
			s.setContentType("application/json");  
			method.setEntity(s); 
			
//			if (paramsMap != null) {
//				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
//				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
//					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
//					paramList.add(pair);
//				}
//				method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
//			}
			response = client.execute(method);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return responseText;
	}

	/**
	 * post json, 返回json
	 * @param url
	 * @param json
	 * @return
	 */
	public static JSONObject post(String url,JSONObject json){  
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);  
		JSONObject response = null;  
		try {  
			StringEntity s = new StringEntity(json.toString());  
			s.setContentEncoding("UTF-8");  
			s.setContentType("application/json");  
			post.setEntity(s);  

			HttpResponse res = client.execute(post);  
			if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){  
				HttpEntity entity = res.getEntity();  

				if (entity != null) {
					String responseText = EntityUtils.toString(entity);
					response = JSONObject.parseObject(responseText);
				}
			}  
		} catch (Exception e) {  
			throw new RuntimeException(e);  
		}  
		return response;  
	}  


	public static JSONObject post(String url,String jsonString){  
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);  
		JSONObject response = null;  
		try {  
			StringEntity s = new StringEntity(jsonString);  
			s.setContentEncoding("UTF-8");  
			s.setContentType("application/json");  
			post.setEntity(s);  

			HttpResponse res = client.execute(post);  
			if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){  
				HttpEntity entity = res.getEntity();  

				if (entity != null) {
					String responseText = EntityUtils.toString(entity);
					response = JSONObject.parseObject(responseText);
				}
			}  
		} catch (Exception e) {  
			throw new RuntimeException(e);  
		}  
		return response;  
	}  

	/**
	 * 基于HttpClient 4.3的�?用get方法
	 *
	 * @param url       提交的URL
	 * @param paramsMap 提交<参数，�?>Map
	 * @return 响应文本内容
	 */
	public static String get(String url, Map<String, String> paramsMap) {
		CloseableHttpClient client = HttpClients.createDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {
			String paramStr = "";
			if (paramsMap != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
					paramList.add(pair);
				}

				//转换为键值对  
				paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramList, ENCODING));  
			}
			//创建Get请求  
			HttpGet httpGet = new HttpGet(url+"?"+paramStr);  
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return responseText;
	}
}
